package io.yyxx.boot.util;

import io.yyxx.boot.business.entity.billDataEntity.BillQueryParams;
import io.yyxx.boot.business.entity.billDataEntity.BillSettlementResponse;
import io.yyxx.boot.business.entity.billDataEntity.CarResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.HashMap;

import java.util.Map;

/**
 * 用车账单查询
 */
@Component
@Slf4j
public class CarBillApi {

    //从配置文件中获取URL
    @Value("${ali.url.car}")
    private String carUrl;

    private final RestTemplate restTemplate = new RestTemplate();

    public CarResponse queryBillSettlement(BillQueryParams params, String appKey, String corpToken) {
        // 参数校验
        if (params.getPageSize() > 100) {
            throw new IllegalArgumentException("page_size不能超过100");
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

        // 构建查询参数
        Map<String, Object> urlParams = new HashMap<>();
        urlParams.put("app_key", appKey);
        urlParams.put("page_no", params.getPageNo());
        urlParams.put("page_size", params.getPageSize());
        if (params.getPeriodStart() != null) {
            urlParams.put("period_start", params.getPeriodStart());
        }

        if (params.getPeriodEnd() != null) {
            urlParams.put("period_end", params.getPeriodEnd());
        }

        if (params.getScrollId() != null) {
            urlParams.put("scroll_id", params.getScrollId());
        }

        if (params.getBillBatch() != null) {
            urlParams.put("bill_batch", params.getBillBatch());
        }

        if (corpToken.isEmpty()) {
            urlParams.put("so_corp_token", corpToken);
        }
        // 构建URL模板，并添加参数
        String url = String.format(
                carUrl + "?app_key=%s&page_no=%d&page_size=%d&period_start=%s&period_end=%s&scroll_mod=%s&so_corp_token=%s",
                appKey,
                params.getPageNo(),
                params.getPageSize(),
                params.getPeriodStart(),
                params.getPeriodEnd(),
                params.getScrollMod(),
                corpToken
        );
        // System.out.println(url);
        // 构建请求
        HttpEntity<?> entity = new HttpEntity<>(headers);
        ResponseEntity<CarResponse> response = restTemplate.exchange(
                url,
                HttpMethod.GET,
                entity,
                CarResponse.class,
                urlParams);
        return response.getBody();
    }
}